<?php
class BirthdayNotification extends CWidget {

	public $dayOffset=25;

	public function run()
	{
		$date=getdate();
		$dayOfYear=$date['yday'];
		$targetDayOfYear=$dayOfYear+$this->dayOffset;
		$criteria=new CDbCriteria();
		if($targetDayOfYear<=365){
			$criteria->addBetweenCondition('DAYOFYEAR(dateOfBirth)', $dayOfYear, $targetDayOfYear);
			$criteria->order='DAYOFYEAR(dateOfBirth) asc';
		}else{
			$mixCriteria=new CDbCriteria();
			$mixCriteria->addBetweenCondition('DAYOFYEAR(dateOfBirth)', $dayOfYear, 365, 'OR');
			$mixCriteria->addBetweenCondition('DAYOFYEAR(dateOfBirth)', 0, $targetDayOfYear-365, 'OR');
			$criteria->mergeWith($mixCriteria);
			$criteria->order='if(DAYOFYEAR(dateOfBirth)>'.$dayOfYear.',DAYOFYEAR(dateOfBirth),DAYOFYEAR(dateOfBirth)+365) asc';
		}
		if(!Yii::app()->user->checkAccess('customerInfoView')){
			if(User::getCurrentUser()->teamLeader){
				$criteria->compare('teamId', User::getCurrentUser()->teamId);
			}else{
				$criteria->compare('createUserId', User::getCurrentUser()->id);				
			}
		}
		$customersDb=Customer::model()->findAll($criteria);
		$customers=array();
		foreach ($customersDb as $customerDb){
			$birthday=getdate(CDateTimeParser::parse($customerDb->dateOfBirth,'d/M/yyyy'));
			$customers[]=array(
				'id'=>$customerDb->id,
				'name'=>$customerDb->getFullname(),
				'dateOfBirth'=>$customerDb->dateOfBirth,
				'daysLeft'=>$birthday['yday']>=$dayOfYear?$birthday['yday']-$dayOfYear:$birthday['yday']-$dayOfYear+365,
			);
		}
		$this->render('birthdayNotification',array('customers'=>$customers,'dayOffset'=>$this->dayOffset));
	}
}